package com.liziguo.lzgfp.system.codec;

import com.liziguo.lzgfp.system.util.AESUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

/**
 * @Author: Liziguo
 * @Date: 2021/12/27 15:14
 */
public class AESCodec extends MessageToMessageCodec<ByteBuf, ByteBuf> {

    private final String aesKey;

    public AESCodec(String aesKey) {
        this.aesKey = aesKey;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        list.add(Unpooled.copiedBuffer(AESUtil.encrypt(bytes, aesKey)));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        list.add(Unpooled.copiedBuffer(AESUtil.decrypt(bytes, aesKey)));
    }
}
